#include "mystdio.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>




my_file* my_fopen(const char* path, const char* flag)
{
    int iscreate = 0;
    int flag1 = 0;
    if(strcmp(flag,"r") == 0)
    {
        flag1 = O_RDONLY;
    }
    else if(strcmp(flag,"w") == 0)
    {
        flag1 = O_WRONLY | O_CREAT | O_TRUNC;
        iscreate = 1;
    }
    else if(strcmp(flag,"a") == 0)
    {
        flag1 = O_WRONLY | O_CREAT | O_APPEND;
        iscreate = 1;
    }
    else{}
    int fd = 0;
    if(iscreate)
        fd = open(path,flag1,0666);
   else
        fd = open(path,flag1);
    if(fd<0) return NULL;

    my_file* pf = (my_file*)malloc(sizeof(my_file));
    pf->fileno = fd;
    pf->pos = 0;
    pf->flag = Fflush_line;
    pf->cpa = LINE_SIZE;
    return pf;
}

void  my_fflush(my_file* fp)
{
    write(fp->fileno,fp->cache,fp->pos);
    fp->pos = 0;
}

size_t my_fwrite(my_file* fp,const char* data,size_t len)
{
    memcpy(fp->cache+fp->pos,data,len);
    fp->pos+=len;
    
    if(fp->flag & Fflush_line && fp->cache[fp->pos-1] == '\n')
    {
        my_fflush(fp);
    }
    return len;
}
void  my_fclose(my_file* fp)
{
    my_fflush(fp);
    close(fp->fileno);
    free(fp);
}
